<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Swoole\Process;
use Swoole\Coroutine\Server\Connection;
use Swoole\Coroutine;

class Log extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'write:log';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'swoole write log';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $pool = new Process\Pool(2);
        $pool->set(['enable_coroutine' => true]);

        $pool->on("workerStart",function ($pool, $id){
            $server = new \Swoole\Coroutine\Server('127.0.0.1', 9501, false, true);

            //收到15信号关闭服务
            Process::signal(SIGTERM, function () use ($server) {
                $server->shutdown();
            });
            $server->handle(function (Connection $conn) use ($server, $id){
                while (true) {
                    var_dump("aaa");
                    $data = $conn->recv();
                    var_dump("bbbb");
                    if (empty($data)) {
                        // 关闭连接
                        $conn->close();
                        break;
                    } else {
                       // $server->task();
                        file_put_contents("/Users/yanxs/code/logs/test.log",$data,FILE_APPEND);
                    }
                    var_dump($id);
                    //发送数据
                    $conn->send('hello');

                    //Coroutine::sleep(1);
                }
            });
            //开始监听端口
            $server->start();
        });
        $pool->start();
    }
}
